package cn.ycl.auth.biz.usercenter.controller;

import cn.ycl.auth.biz.usercenter.entity.RegisterParam;
import cn.ycl.auth.biz.usercenter.entity.WeiXinCheckUrl;
import cn.ycl.auth.biz.usercenter.service.LoginService;
import cn.ycl.auth.utils.SHA1;
import cn.ycl.constans.Result;
import cn.ycl.entity.LoginParam;
import cn.ycl.syslog.OperationEnum;
import cn.ycl.syslog.SystemLog;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 登录接口
 *
 * @Author YuanChangLiang
 * @Date 2020/11/4 10:25
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    LoginService loginService;

    @PostMapping("/login")
    @SystemLog(value = "用户登录", type = OperationEnum.LOG_IN)
    @Transactional(rollbackFor = Exception.class)
    public Result loginByPassword(@RequestBody LoginParam loginParam, HttpServletRequest request) {
        return loginService.loginQuery(loginParam, request);
    }

    @SystemLog(value = "用户注册", type = OperationEnum.LOG_IN)
    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    public Result register(@RequestBody RegisterParam registerParam) {
        return loginService.register(registerParam);
    }


    @GetMapping("/hello")
    public String loginHello() {
        return "进来了loginHello";
    }

    /**
     * 微信验证url
     */
    @GetMapping("/checkUrl")
    public String checkUrl(WeiXinCheckUrl weiXinCheckUrl) {
        //与申请测试号网站填写的token对应
        String token = "JustDoIt";
        List<String> paramList = new ArrayList<>();
        paramList.add(weiXinCheckUrl.getNonce());
        paramList.add(weiXinCheckUrl.getTimestamp());
        paramList.add(token);
        //按字节排序
        Collections.sort(paramList);
        //按顺序拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        paramList.forEach(stringBuilder::append);
        //sha1加密
        String encode = SHA1.encode(stringBuilder.toString());
        System.out.println("微信消息发过来了：" + weiXinCheckUrl.getEchostr());
        if (encode.equals(weiXinCheckUrl.getSignature())) {
            return weiXinCheckUrl.getEchostr();
        } else {
            return "";
        }
    }

}
